﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ManCoRepository.cs" company="DST Nexdox">
//   Copyright (c) DST Nexdox. All rights reserved.
// </copyright>
// <summary>
//   Defines the ManCoRepository type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace UnityRepository.Repositories
{
  using System;
  using System.Collections.Generic;
  using System.Data.Entity;
  using System.Linq;
  using EFRepository;
  using Entities;
  using Exceptions;
  using UnityRepository.Contexts;
  using UnityRepository.Interfaces;

  public class ManCoRepository : BaseEfRepository<ManCo>, IManCoRepository
  {
    public ManCoRepository(String connectionString)
      : base(new UnityDbContext(connectionString))
    {
    }

    public ManCo GetManCo(Int32 id)
    {
      return (from a in Entities where a.Id == id select a).FirstOrDefault();
    }

    public ManCo GetManCo(String code)
    {
      return (from a in Entities where a.Code == code select a).FirstOrDefault();
    }

    public IList<ManCo> GetManCos()
    {
      return Entities.OrderBy(m => m.Description).ToList();
    }

    public void Update(Int32 docTypeId, String name, String description)
    {
      ManCo docType = this.GetManCo(docTypeId);
      if (docType == null)
      {
        throw new UnityException("man co id not valid");
      }

      docType.UpdateManCo(name, description);
      this.Update(docType);
    }

    public IList<ManCo> GetManCos(IList<Int32> manCoIds)
    {
      return (from a in Entities where manCoIds.Contains(a.Id) select a).AsNoTracking().ToList();
    }

    public IEnumerable<ManCo> GetManCos(Int32 domicileId)
    {
      return (from a in Entities where a.DomicileId == domicileId select a).ToList();
    }

    public IList<ManCo> GetManCosByUserId(String userId)
    {
      return
        (from a in Entities where a.Users.Any(x => x.UserId == userId) select a).OrderBy(o => o.Description)
          .AsNoTracking()
          .ToList();
    }

    public ManCo GetManCoForCart(String cartId)
    {
      return Entities.FirstOrDefault(mc => mc.Documents.Any(d => d.CartItems.Any(ci => ci.CartId == cartId)));
    }
  }
}
